package com.baoyouqun.API.gps;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baoyouqun.entity.User;
import com.baoyouqun.service.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.Principal;

@SaIgnore
@RestController
@RequestMapping("/api/location")
@Api(tags = "地理位置工具接口")
public class LocationController {

    @Resource
    private LocationService locationService;
    @Resource
    private UserService userService;

    @GetMapping("/to-city")
    @ApiOperation("根据经纬度获取城市信息")
    public SingleResponse<JsonNode> getCityByLocation(
            @ApiParam(value = "经度", required = true) @RequestParam Double longitude,
            @ApiParam(value = "纬度", required = true) @RequestParam Double latitude) throws IOException {
        return locationService.getCityByLocation(longitude, latitude);
    }

    @PostMapping("/sync-location")
    @ApiOperation("同步用户经纬度位置")
    public Response syncUserLocation(@Valid @RequestBody UserLocationDTO locationDTO, Principal principal) {
        // 获取当前登录用户ID（实际项目中需根据认证方式调整）
        String userId = principal.getName();
        User user = userService.getById(userId);
        if (user == null) {
            return Response.buildFailure("400001", "用户不存在");
        }
        user.setLongitude(locationDTO.getLongitude());
        user.setLatitude(locationDTO.getLatitude());
        userService.updateById(user);
        return Response.buildSuccess();
    }
}